#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include "../../src/locks/spinlock.h"

#define NUM_THREADS 4
#define ITERATIONS 1000000

spinlock_t lock;
long shared_counter = 0;

void* thread_func(void* arg) {
    for (int i = 0; i < ITERATIONS; i++) {
        spinlock_lock(&lock);
        shared_counter++;
        spinlock_unlock(&lock);
    }
    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];
    struct timespec start, end;
    
    spinlock_init(&lock);
    clock_gettime(CLOCK_MONOTONIC, &start);
    
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, thread_func, NULL);
    }
    
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    
    clock_gettime(CLOCK_MONOTONIC, &end);
    
    double time_spent = (end.tv_sec - start.tv_sec) +
                       (end.tv_nsec - start.tv_nsec) / 1e9;
    
    printf("Time spent: %.2f seconds\n", time_spent);
    printf("Operations per second: %.2f\n", 
           (NUM_THREADS * ITERATIONS) / time_spent);
    printf("Final counter value: %ld\n", shared_counter);
    
    return 0;
} 